<?php


namespace App\Libraries\Queue;


use App\Repositories\OrderCustoms;
use Exception;
use Illuminate\Support\Facades\Log;
use PhpAmqpLib\Message\AMQPMessage;
use SimpleXMLElement;

class ReceiptHandleMessage implements HandleMessage
{

    /**
     * @param AMQPMessage $message
     * @author luffyzhao@vip.126.com
     */
    public function handle(AMQPMessage $message)
    {
        try{
            $element = simplexml_load_string($message->getBody());
            call_user_func_array([$this, $element->getName()], [$element]);
        }catch (Exception $exception){
            Log::error(sprintf("回执消费失败:%s" , $exception->getMessage()));
        }
    }

    /**
     * 清单回执
     * @param SimpleXMLElement $element
     * @author luffyzhao@vip.126.com
     */
    protected function CEB622Message(SimpleXMLElement $element){
        $array = $this->toArray($element);
        if(!isset($array['InventoryReturn'][0])){
            $array['InventoryReturn'] = [$array['InventoryReturn']];
        }
        foreach ($array['InventoryReturn'] as $return){
            app(OrderCustoms::class)->returnCustoms($return);
        }
    }


    /**
     * @param SimpleXMLElement $element
     * @return mixed
     * @author luffyzhao@vip.126.com
     */
    protected function toArray(SimpleXMLElement $element){
        return \GuzzleHttp\json_decode(\GuzzleHttp\json_encode($element), true);
    }
}